package poi;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.Level;

class LogFormatter extends Formatter {
	private static Logger log = Logger.getLogger("POISystem.LogFormatter");
	
	static public void setLogFormat() {
		if (log.getHandlers().length==0) {
			LogFormatter lf = new LogFormatter();
			Handler hnd;
			try {
				SimpleDateFormat dtFormat = new SimpleDateFormat("dd.MM.yyyy");
				String dt=dtFormat.format(java.util.Calendar.getInstance().getTime());
				hnd = new FileHandler("POISystem_" + dt + ".log", true);
				hnd.setFormatter(lf);
				log.addHandler(hnd);
				log.setLevel(Level.ALL);
			} catch (SecurityException e) {
				log.severe("Can't set up log formater.");
			} catch (IOException e) {
				log.severe("Can't set up log formater.");
			}
		}
	}
	
	private String getLevelName(Level v) {
		if (v.intValue() == Level.SEVERE.intValue()) {
			return "ERROR";
		}
		if (v.intValue() == Level.FINEST.intValue()) {
			return "DEBUG";
		}
		return v.toString();
	}
	
	public String format(LogRecord rec)
	{
		StringBuffer buf = new StringBuffer(1000);
		buf.append(calcDate(rec.getMillis()));
		buf.append(" [");
		buf.append(getLevelName(rec.getLevel()));
		buf.append("] (");
		buf.append(rec.getSourceClassName());
		buf.append(".");
		buf.append(rec.getSourceMethodName());
		buf.append(") ");
		buf.append(formatMessage(rec));
		buf.append("\n");
		return buf.toString();
	}

	private String calcDate(long millisecs)
	{
		SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
		Date resultdate = new Date(millisecs);
		return dateFormat.format(resultdate);
	}

}
